package person.bangbang.im.Androidgin.Util;
/**
 * 
 * @author bangbang.song@gmail
 *
 */
public class CircleBuffer {
	private static final String TAG = "CircleBuffer";
	private  int vol = 1024;  // default to 1k.
	private  char[] buffer;
	private  int head;
	private  int tail;
	
	public CircleBuffer(int volume) {
		vol = volume;
		buffer = new char[vol];
		head = vol - 1;
		tail = vol - 1;
	}
	public CircleBuffer() {
		buffer = new char[vol];
		head = vol - 1;
		tail = vol - 1;
	}
	public  void write2buffer(String msg) {
		// TODO optimize
		int len = msg.length();
		if (len >= vol) { // trip is only
			for (int i = 0 ; i < vol ; i++) {
				buffer[i] = msg.charAt(i);
			}
			tail = vol - 1;
			head = 0;
			
			return ;
		}

		if (isEmpty()) {
			//                               h
			//                               t
			// +-----------------------------+
			
			int j = 0;
			head = vol - len;
			for (int i = head ; i < vol  ; i++) {
				buffer[i] = msg.charAt(j++);
			}
			// head has set, tail is the same.
		} else if (isFull()) {
			//          th              
			// +--------**--------------+
			if (len <= head) { // no wrap
				int newh = head - len;
				int j = 0;
				for (int i = newh ; i < head ; i++) {
					buffer[i] = msg.charAt(j++);
				}
				head = newh;
				tail = head == 0 ? vol -1 : head -1;
			} else { // wrap it.
				int newh = vol - 1 - (len - head -1);
				int j = 0;
				for (int i = newh ; i < vol ; i++)	{
					buffer[i] = msg.charAt(j++);
				}
				for (int i = 0 ; i < head ; i++) {
					buffer[i] = msg.charAt(j++);
				}
				head = newh;
				tail = head - 1;
			}
			

		} else { // non-empty non-full
			//           h              t
			// +---------*--------------+
			if (len <= head) { // no wrap
				int newh = head - len;
				int j = 0;
				for (int i = newh ; i < head ; i++) {
					buffer[i] = msg.charAt(j++);
				}
				head = newh;
			} else { // wrap it.
				int newh = vol - 1 - (len - head -1);
				int i = 0;
				for (int pos = newh ; pos < vol ; pos++)	{
					buffer[pos] = msg.charAt(i++);
				}
				for (int pos = 0 ; pos < head ; pos++) {
					buffer[pos] = msg.charAt(i++);
				}
				head = newh;
				tail = head - 1 ;
			}
		}
		
	}
	
	public String dump(){
		if (!isFull()) {
			char[] c = new char[vol - head];
			int j = 0;
			for (int i = head ; i < vol; i++) {
				c[j++] = buffer[i];
			}
			
			return new String(c);
		} else { // full
			char[] c = new char[vol];
			int j = 0;
			for (int i = head ; i < vol ; i++) {
				c[j++] = buffer[i];
			}
			for (int i = 0 ; i < head	; i++){
				c[j++] = buffer[i];
			}
			
			return new String(c);
		}
	}

	
	public  boolean isFull(){
		// TODO optimize
		if ((tail + 1) % vol == head ) {
			return true;
		}
					
		return false;
	}
	public boolean isEmpty(){
		return (head == tail);
	}
}
